<template>
  <div class="flex justify-between">
    <div class="text-base font-bold">找车</div>
    <el-button class="custom-button" type="primary" plain @click="goBack">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="20" height="20" fill="rgba(64,158,254,1)">
        <path
          d="M19.0001 10.0001L19.0003 19L17.0003 19L17.0002 12.0001L9.41409 12V17.4142L2.99988 11L9.41409 4.58578L9.41409 10L19.0001 10.0001Z">
        </path>
      </svg>返回
    </el-button>
  </div>
  <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
    <el-form-item label="装货地" prop="loadingPlaceCode">
      <el-cascader v-model="queryParams.loadingPlaceCode" :options="addressList" :props="{ checkStrictly: true }"
        filterable placeholder="请选择装货地" class="!w-400px"></el-cascader>
    </el-form-item>
    <el-form-item label="卸货地" prop="unloadPlaceCode">
      <el-cascader v-model="queryParams.unloadPlaceCode" :options="addressList" :props="{ checkStrictly: true }"
        filterable placeholder="请输入卸货地" class="!w-400px"></el-cascader>
    </el-form-item>
    <el-form-item label="车辆状态" prop="vehicleStatus">
      <el-select clearable v-model="queryParams.vehicleStatus" placeholder="请选择车辆状态" class="!w-200px">
        <el-option v-for="dict in getIntDictOptions(DICT_TYPE.DRIVER_VEHICLE_STATUS)" :key="dict.value"
          :label="dict.label" :value="dict.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="司机状态" prop="driverStatus">
      <el-select clearable v-model="queryParams.driverStatus" placeholder="请选择司机状态" class="!w-200px">
        <el-option v-for="dict in getIntDictOptions(DICT_TYPE.DRIVER_VEHICLE_STATUS)" :key="dict.value"
          :label="dict.label" :value="dict.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="时间范围" prop="timeRange">
      <el-button-group class="mr-12px">
        <el-button type="primary" v-for="item in timeTypeList" :key="item.value"
          :plain="timeType===item.value ? false : true" @click="timeTypeChange(item.value)">
          {{item.label}}
        </el-button>
      </el-button-group>
      <el-date-picker :disabled="timeType!=='customize'" v-model="queryParams.timeRange " value-format="YYYY-MM-DD"
        start-placeholder="开始时间" end-placeholder="结束时间" type="daterange" class="!w-240px" />
    </el-form-item>
    <el-form-item label="车牌号" prop="vehicleNo">
      <el-input clearable :maxlength="8" v-model="queryParams.vehicleNo" placeholder="请输入车牌号" @keyup.enter="handleQuery"
        class="!w-200px" />
    </el-form-item>
    <el-form-item label="手机号" prop="driverPhone">
      <el-input clearable :maxlength="11" v-model="queryParams.driverPhone" placeholder="请输入手机号"
        @keyup.enter="handleQuery" class="!w-200px" />
    </el-form-item>
    <el-form-item label="业务类型" prop="bizType">
      <el-select v-model="queryParams.bizType" placeholder="请选择业务类型" class="!w-200px">
        <el-option v-for="dict in getIntDictOptions(DICT_TYPE.BIZ_TYPE)" :key="dict.value" :label="dict.label"
          :value="dict.value" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleQuery">
        搜索
      </el-button>
      <el-button @click="resetQuery">
        重置
      </el-button>
      <el-button type="common" plain @click="handleExport" :loading="exportLoading" v-hasPermi="['findCar:export']">
        导出
      </el-button>
    </el-form-item>
  </el-form>
  <el-button class="mb-16px" v-hasPermi="['findCar:batchAddLine']" type="primary"
    @click="batchAddLine">批量添加到线路</el-button>
  <el-table ref="tableRef" v-loading="loading" :data="list" border stripe
    :header-cell-style="{ background: '#F3F4F7', color: '#555' }">
    <el-table-column type="selection" width="55" />
    <el-table-column label="车牌号" align="center" prop="vehicleNo" min-width="100" fixed="left"
      :show-overflow-tooltip="true" />
    <el-table-column label="司机姓名" align="center" prop="driverName" min-width="150" :show-overflow-tooltip="true" />
    <el-table-column label="电话" align="center" prop="driverPhone" min-width="150" :show-overflow-tooltip="true" />
    <el-table-column label="车辆状态" align="center" prop="vehicleStatus" min-width="100" :show-overflow-tooltip="true">
      <template #default="{ row }">
        <span class="status" :class="statusStyle(row.vehicleStatus)"></span>
        <span :class="textStyle(row.vehicleStatus)">{{getDictLabel(DICT_TYPE.DRIVER_VEHICLE_STATUS,
          row.vehicleStatus?.toString())}}</span>
      </template>
    </el-table-column>
    <el-table-column label="司机状态" align="center" prop="driverStatus" min-width="150" :show-overflow-tooltip="true">
      <template #default="{ row }">
        <span class="status" :class="statusStyle(row.driverStatus)"></span>
        <span :class="textStyle(row.driverStatus)">{{getDictLabel(DICT_TYPE.DRIVER_VEHICLE_STATUS,
          row.driverStatus?.toString())}}</span>
      </template>
    </el-table-column>
    <el-table-column label="身份证号" align="center" prop="driverIdCard" min-width="150" :show-overflow-tooltip="true" />
    <el-table-column label="运输车次" align="center" prop="transportCount" min-width="100" :show-overflow-tooltip="true">
    </el-table-column>
    <el-table-column label="最近拉运时间" align="center" prop="recentShippingTime" min-width="200"
      :show-overflow-tooltip="true" />
    <el-table-column label="操作" align="center" width="110" fixed="right">
      <template #default="{ row }">
        <el-button v-hasPermi="['findCar:addLine']" type="primary" link @click="addLine(row)">添加到线路</el-button>
      </template>
    </el-table-column>
  </el-table>
  <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
    @pagination="getList" />
  <AddLineDialog ref="addLineDialogRef"></AddLineDialog>
</template>
<script setup lang="ts" name="findTrain">
  import { cloneDeep } from 'lodash'
  import download from '@/utils/download'
  import * as AreaApi from '@/api/system/area'
  import AddLineDialog from './addLineDialog.vue'
  import { formatDate } from '@/utils/formatTime.ts'
  import * as goodsSourceApi from '@/api/transportation/goodsSource'
  import { useCommonStore, useCommonStoreOut } from '@/store/modules/common'
  import { DICT_TYPE, getIntDictOptions, getDictLabel } from '@/utils/dict'
  const emit = defineEmits(['subPage'])
  const commonStore = useCommonStore()
  const exportLoading = ref(false)
  const message = useMessage()
  const queryFormRef = ref()
  const loading = ref(false)
  const list = ref([])
  const total = ref(0)
  const addressList = ref([])
  const addLineDialogRef = ref()
  const tableRef = ref()
  const queryParams = ref({
    sourceOrderId: undefined,
    loadingPlaceCode: [],
    unloadPlaceCode: [],
    vehicleStatus: 0,
    driverStatus: 0,
    vehicleNo: undefined,
    driverPhone: undefined,
    bizType: undefined,
    timeRange: [],
    pageNo: 1,
    pageSize: 10,
  })
  const timeType = ref('30')
  const timeTypeList = reactive([
    {
      label: '近3天',
      value: '3'
    },
    {
      label: '近7天',
      value: '7'
    },
    {
      label: '近30天',
      value: '30'
    },
    {
      label: '自定义',
      value: 'customize'
    }
  ])

  const statusStyle = computed(() => {
    return (status) => {
      return status === 0 ? 'idle' : 'busy'
    }
  })

  const textStyle = computed(() => {
    return (status) => {
      return status === 0 ? 'color-idle' : 'color-busy'
    }
  })

  const getAreaTree = async () => {
    const result = await AreaApi.getAreaTree()
    addressList.value = handleResult(result)
  }

  const handleResult = (result) => {
    result.forEach(e => {
      e.value = e.id
      e.label = e.name
      if (e.children?.length) {
        handleResult(e.children)
      }
    })
    return result
  }

  const timeTypeChange = (value) => {
    timeType.value = value
    if (value !== 'customize') {
      const timeDiff = timeType.value * 24 * 3600 * 1000
      const current = new Date().getTime()
      const startTime = `${formatDate(current - timeDiff, 'YYYY-MM-DD')} 00:00:00`
      const endTime = `${formatDate(current, 'YYYY-MM-DD')} 23:59:59`
      queryParams.value.timeRange = [startTime, endTime]
    }
  }

  const initParams = () => {
    if (commonStore.getFormData) {
      queryParams.value.bizType = commonStore.getFormData.bizType
      queryParams.value.sourceOrderId = commonStore.getFormData.id
      queryParams.value.loadingPlaceCode = [commonStore.getFormData.loadingPlaceProvinceCode, commonStore.getFormData.loadingPlaceCityCode, commonStore.getFormData.loadingPlaceCountyCode, commonStore.getFormData.loadingPlaceTownCode]
      queryParams.value.unloadPlaceCode = [commonStore.getFormData.unloadingPlaceProvinceCode, commonStore.getFormData.unloadingPlaceCityCode, commonStore.getFormData.unloadingPlaceCountyCode, commonStore.getFormData.unloadingPlaceTownCode]
    }
  }

  const getBody = () => {
    const data = cloneDeep(queryParams.value)
    data['loadingPlaceProvinceCode'] = data.loadingPlaceCode[0]
    data['loadingPlaceCityCode'] = data.loadingPlaceCode[1]
    data['loadingPlaceCountyCode'] = data.loadingPlaceCode[2]
    data['loadingPlaceTownCode'] = data.loadingPlaceCode[3]
    data['unloadingPlaceProvinceCode'] = data.unloadPlaceCode[0]
    data['unloadingPlaceCityCode'] = data.unloadPlaceCode[1]
    data['unloadingPlaceCountyCode'] = data.unloadPlaceCode[2]
    data['unloadingPlaceTownCode'] = data.unloadPlaceCode[3]
    if (timeType.value !== 'customize') {
      const timeDiff = timeType.value * 24 * 3600 * 1000
      const current = new Date().getTime()
      data['startTime'] = `${formatDate(current - timeDiff, 'YYYY-MM-DD')} 00:00:00`
      data['endTime'] = `${formatDate(current, 'YYYY-MM-DD')} 23:59:59`
    }
    if (timeType.value === 'customize') {
      data['startTime'] = `${formatDate(data.timeRange[0], 'YYYY-MM-DD')} 00:00:00`
      data['endTime'] = `${formatDate(data.timeRange[1], 'YYYY-MM-DD')} 23:59:59`
    }
    delete data.loadingPlaceCode
    delete data.unloadPlaceCode
    delete data.timeRange
    return data
  }

  const getList = async () => {
    if (timeType.value === 'customize') {
      const MAX_TIME = 90 * 24 * 3600 * 1000
      if (queryParams.value.timeRange.length !== 2) {
        message.warning('自定义时间不能为空')
        return
      }
      const startTime = new Date(`${formatDate(queryParams.value.timeRange[0], 'YYYY-MM-DD')} 00:00:00`).getTime()
      const endTime = new Date(`${formatDate(queryParams.value.timeRange[1], 'YYYY-MM-DD')} 23:59:59`).getTime()
      if (endTime - startTime > MAX_TIME) {
        message.warning('自定义时间最大不超过90天')
        return
      }
    }
    if (!queryParams.value.loadingPlaceCode?.length) {
      message.warning('装货地不能为空')
      return
    }
    if (!queryParams.value.unloadPlaceCode?.length) {
      message.warning('卸货地不能为空')
      return
    }
    if (!queryParams.value.bizType) {
      message.warning('业务类型不能为空')
      return
    }
    try {
      loading.value = true
      const res = await goodsSourceApi.getOrdersByGoodsSourceId(getBody())
      list.value = res.list || []
      total.value = res.total || 0
    } finally {
      loading.value = false
    }
  }

  const handleQuery = () => {
    queryParams.pageNo = 1
    getList()
  }

  const resetQuery = () => {
    timeType.value = '30'
    tableRef.value.clearSelection()
    queryFormRef.value.resetFields()
    timeTypeChange(timeType.value)
    initParams()
    handleQuery()
  }

  const addLine = (row) => {
    addLineDialogRef.value.open([toRaw(row)])
  }

  const batchAddLine = () => {
    const list = tableRef.value.getSelectionRows()
    if (list.length === 0) {
      message.warning('至少勾选一条数据')
      return
    }
    if (list.length >= 20) {
      message.warning('最多勾选20条数据')
      return
    }
    addLineDialogRef.value.open(list)
  }

  const goBack = () => {
    emit('subPage', 0)
  }

  const handleExport = async () => {
    if (timeType.value === 'customize') {
      const MAX_TIME = 90 * 24 * 3600 * 1000
      if (queryParams.value.timeRange.length !== 2) {
        message.warning('自定义时间不能为空')
        return
      }
      const startTime = new Date(`${formatDate(queryParams.value.timeRange[0], 'YYYY-MM-DD')} 00:00:00`).getTime()
      const endTime = new Date(`${formatDate(queryParams.value.timeRange[1], 'YYYY-MM-DD')} 23:59:59`).getTime()
      if (endTime - startTime > MAX_TIME) {
        message.warning('自定义时间最大不超过90天')
        return
      }
    }
    if (!queryParams.value.loadingPlaceCode?.length) {
      message.warning('装货地不能为空')
      return
    }
    if (!queryParams.value.unloadPlaceCode?.length) {
      message.warning('卸货地不能为空')
      return
    }
    if (!queryParams.value.bizType) {
      message.warning('业务类型不能为空')
      return
    }
    try {
      await message.exportConfirm()
      exportLoading.value = true
      const data = await goodsSourceApi.exportOrdersByGoodsSourceId(getBody())
      download.excel(data, '找车列表.xls')
    } finally {
      exportLoading.value = false
    }
  }

  onMounted(async () => {
    try {
      loading.value = true
      await getAreaTree()
      if (commonStore.getFormData) {
        initParams()
        timeTypeChange(timeType.value)
        await getList()
      }
    } finally {
      loading.value = false
    }
  })
</script>
<style lang="scss" scoped>
  :deep(.custom-button.el-button--primary.is-plain) {
    background-color: #ffffff !important;
  }

  :deep(.custom-button.el-button:focus),
  :deep(.custom-button.el-button:hover) {
    background-color: #ffffff !important;
    color: var(--el-color-primary) !important;
  }

  .color-idle {
    color: #409EFE;
  }

  .color-busy {
    color: #F78600;
  }

  .idle {
    background-color: rgba(40, 147, 255, 0.3);

    &::after {
      background-color: #409EFE;
    }
  }

  .busy {
    background-color: rgba(247, 134, 0, 0.3);

    &::after {
      background-color: #F78600;
    }
  }

  .status {
    display: inline-block;
    position: relative;
    width: 10px;
    height: 10px;
    border-radius: 5px;
    margin-right: 4px;

    &::after {
      content: '';
      display: inline-block;
      position: absolute;
      top: 2px;
      left: 2px;
      width: 6px;
      height: 6px;
      border-radius: 3px;
    }
  }
</style>